package com.eight.travel.config;


import com.eight.travel.utils.MyRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Q小旭
 * @version 1.0
 */
//配置类
@Configuration
public class ShiroConfig {

    //结合springboot环境，配置自定义realm并设置运行环境SecurityManager
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean1 = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean1.setSecurityManager(defaultWebSecurityManager);
        //将权限的拦截设置在map中
        Map<String,String> map = new HashMap<>();
        //访问goods路径时,必须要有findAll权限
        map.put("/user/register","perms[/findAll]");
        //对于没有权限的访问，设置一个跳转页面
        shiroFilterFactoryBean1.setUnauthorizedUrl("/#/unauth");
        //对于没有登录的访问，设置一个登录页面
        shiroFilterFactoryBean1.setLoginUrl("/#/login");
        shiroFilterFactoryBean1.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean1;

    }

    //ShiroFilterFactoryBean:将SecurityManager设置为shiro运行环境
    //并且将realm实例设置到SecurityManager里
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("myrealm") MyRealm myRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(myRealm);
        return defaultWebSecurityManager;

    }
    //创建自定义realm实例
    @Bean(name = "myrealm")
    public MyRealm myRealm(){  //交给spring管理
        return new MyRealm();
    }

    //开启shiro注解
    //使用springaop创建代理
//    @Bean
//    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
//        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
//        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
//        return defaultAdvisorAutoProxyCreator;
//    }
//
//    //shiro注解
//    @Bean
//    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager defaultWebSecurityManager){
//        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
//        authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager);
//        return authorizationAttributeSourceAdvisor;
//    }
}
